package com.narbeshuber.tablet.lasalara.listadapters;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.narbeshuber.tablet.lasalara.LasaLaraActivity;
import com.narbeshuber.tablet.lasalara.R;
import com.narbeshuber.tablet.lasalara.fragment.BookFragment;
import com.narbeshuber.tablet.lasalara.http.DeleteBookTask;
import com.narbeshuber.tablet.lasalara.http.UpdateBookTask;
import com.narbeshuber.tablet.lasalara.model.Book;
import com.narbeshuber.tablet.lasalara.model.Chapter;

public class BookAdapter extends BaseAdapter {

	private LasaLaraActivity context;
	private List<Book> books;

	public BookAdapter(LasaLaraActivity context, List<Book> books) {
		super();
		this.context = context;
		this.books = books;
		refreshList();
	}
	
	public void refreshList(){
		for(Book book : books){
			calculateAnswerNumbers(book);
		}
		notifyDataSetChanged();
		calculateProgress();
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		final Book book = getItem(position);
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(
					com.narbeshuber.tablet.lasalara.R.layout.bookrow, null);
		}

		// resolve elements
		TextView bookName = (TextView) convertView
				.findViewById(com.narbeshuber.tablet.lasalara.R.id.bookTitle);
		TextView authorName = (TextView) convertView
				.findViewById(com.narbeshuber.tablet.lasalara.R.id.bookAuthor);
		Button deleteButton = (Button) convertView
				.findViewById(R.id.deleteBook);
		Button updateButton = (Button) convertView
				.findViewById(R.id.updateBook);
		TextView bookPercentage = (TextView) convertView
				.findViewById(com.narbeshuber.tablet.lasalara.R.id.bookPercentage);

		// set book title
		bookName.setText(book.getTitle());
		if(LasaLaraActivity.ninjaMode){
			bookName.setTextColor(Color.WHITE);
			authorName.setTextColor(Color.WHITE);
		} else {
			bookName.setTextColor(Color.BLACK);
			authorName.setTextColor(Color.BLACK);
		}
		
		
		// set author name
		if (book.getAuthorName().equalsIgnoreCase("null")) {
			authorName.setText(book.getAuthorEmail());
		} else {
			if (book.getDr().equalsIgnoreCase("true")) {
				authorName.setText("Dr. " + book.getAuthorName()
						+ ", " + book.getInstitution());
			} else {
				authorName.setText(book.getAuthorName() + ", "
						+ book.getInstitution());
			}
		}

		// mode buttons stuff
		
		// delete book
		deleteButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setMessage("Caution! If you created this book, it will be deleted at lasalara.com.")
				       .setCancelable(false).setTitle("Delete book.")
				       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
				    	   public void onClick(DialogInterface dialog, int id) {
				    		   new DeleteBookTask(context).execute(book.getKey(),
										context.getPrefsHelper().getUserKey());
				           }
				       })
				       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.cancel();
				           }
				       }).show();
			}
		});

		// update book
		updateButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				new UpdateBookTask(context).execute(book.getKey());
			}
		});

		// button visibility
		if (BookFragment.deleteMode) {
			deleteButton.setVisibility(View.VISIBLE);
		} else {
			deleteButton.setVisibility(View.GONE);
		}
		
		if (BookFragment.updateMode){
			updateButton.setVisibility(View.VISIBLE);
		} else {
			updateButton.setVisibility(View.GONE);
		}

		// percentages
		int percentage = (int)Math.round((double)book.getAnswered()/(double)book.getTotalQuestions()*100);
		
		if (book.getTotalQuestions() == 0) {
			bookPercentage.setText("");
		} else {
			bookPercentage.setText(percentage + " %");
		}
		return convertView;
	}

	public int getCount() {
		return books.size();
	}

	public Book getItem(int arg0) {
		return books.get(arg0);
	}

	public long getItemId(int arg0) {
		return arg0;
	}

	public void setBooks(List<Book> books) {
		this.books = books;
	}
	
	public void calculateAnswerNumbers(Book book) {
		int answeredQuestions = 0;
		int totalQuestions = 0;
		
		List<Chapter> chapters = context.getDbHelper()
				.getAllChaptersFromBook(book.getKey());
		
		for (Chapter chapter : chapters) {
			answeredQuestions += chapter.getAnswered();
			totalQuestions += chapter.getTotalQuestions();
		}
		book.setAnswered(answeredQuestions);
		book.setTotalQuestions(totalQuestions);
	}

	public void calculateProgress() {
		ProgressBar progressBar = (ProgressBar) context
		.findViewById(R.id.progressLibrary);
		if(progressBar==null){
			return;
		}
		int answeredQuestions = 0;
		int totalQuestions = 0;
		for (Book book : books) {
			List<Chapter> chapters = context.getDbHelper()
					.getAllChaptersFromBook(book.getKey());
			for (Chapter chapter : chapters) {
				answeredQuestions += chapter.getAnswered();
				totalQuestions += chapter.getTotalQuestions();
			}
		}
		int ansPercentage = (int) Math.round((double) answeredQuestions
				/ (double) totalQuestions * 100);
		progressBar.setProgress(ansPercentage);
	}

}
